package com.invest.infra.excel.wrapper.impl;

import com.invest.infra.excel.wrapper.ExCell;
import com.invest.infra.excel.wrapper.ExSheet;
import com.invest.infra.excel.wrapper.ExWorkbook;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Iterator;

public class ExSheetImpl implements ExSheet {

	private ExWorkbook workbook;
	private Sheet poiSheet;
	private int rowCount = 0;
	private int columnCount = 0;
	
	private ExSheetImpl(ExWorkbook workbook,Sheet poiSheet){
		
		this.poiSheet = poiSheet;
		this.workbook = workbook;
	}

	public static ExSheet instance(ExWorkbook workbook,Sheet poiSheet){
		ExSheetImpl instance = new ExSheetImpl(workbook,poiSheet);
		instance.initCount();
		return instance;
	}

	private void initCount() {
		
		if(poiSheet != null ){
			rowCount = this.poiSheet.getLastRowNum() + 1;
			Iterator<Row> iterator = poiSheet.iterator();
			if(iterator != null && iterator.hasNext()){
				Row row = iterator.next();
				columnCount = row.getLastCellNum() + 1;
			}else{
				columnCount = 0;
			}
		}
	}
	
	public ExCell[] getCells(int rowIndex) {
		ExCell[] cells = null;
		if(rowIndex < rowCount){
			
			Row row = poiSheet.getRow(rowIndex);
			if (null != row && columnCount > 0) {
				cells = new ExCell[columnCount];
				for (int index = 0; index < columnCount; index++) {
					Cell me = row.getCell(index, Row.RETURN_BLANK_AS_NULL);
					cells[index] = ExCellImpl.instance(this,me,index);
				}
			}
		}
		return cells;
	}

	@Override
	public void removeRow(int rowIndex) {
		Row row = poiSheet.getRow(rowIndex);
		poiSheet.removeRow(row);
	}

	@Override
	public void shiftRow(int rowIndex) {
		poiSheet.shiftRows(rowIndex+1,poiSheet.getLastRowNum(),-1);
	}

	@Override
	public Row createPoiRow(int rowIndex) {
		return poiSheet.createRow(rowIndex);
	}

	public int getRowCount() {
		return rowCount;
	}

	public String getName() {
		return poiSheet==null ? "" : poiSheet.getSheetName();
	}

	@Override
	public int getColumnCount() {
		
		return columnCount;
		
	}

	@Override
	public Sheet getPoiSheet() {
		return poiSheet;
	}

	@Override
	public ExWorkbook getWorkbook() {
		return workbook;
	}

	@Override
	public void addValidation(String[] dataList, int dataStartRow, int columnIndex) {
		if(ArrayUtils.isEmpty(dataList)){
			return;
		}
		CellRangeAddressList regions = new CellRangeAddressList(dataStartRow, 65535, columnIndex, columnIndex);
		// 生成下拉框list
		DVConstraint constraint = DVConstraint.createExplicitListConstraint(dataList);
		HSSFDataValidation validation = new HSSFDataValidation(regions, constraint);

		poiSheet.addValidationData(validation);

	}
}
